package com.lsy.weizhi2.customview;

import android.content.Context;
import android.os.Handler;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.LayoutParams;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.myutils.HomeBannerCall;
import com.zhy.autolayout.AutoRelativeLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 嗨哟 on 2017/3/13.
 */
public class MyBanner extends AutoRelativeLayout {
    private Context context;
    private View view;
    private ViewPager vp_banner;
    private LinearLayout banner_points;
    private List<?> list;
    private List<ImageView> list_iv;
    private ImagePagerAdapter imagePagerAdapter;
    private HomeBannerCall homeBannerCall;
    private int flag;
    private int index;
    private int Time = 5000;
    private boolean isStart;
    private Handler handler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            //Log.i("MyBanner","index==r=="+index);
            index++;
            vp_banner.setCurrentItem(index);
            //Log.i("MyBanner","isStart=="+isStart);
            if (isStart) {
                handler.postDelayed(runnable, Time);
            }
        }
    };

    public MyBanner(Context context) {
        super(context);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.mybanner, this, true);
    }

    public MyBanner(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        view = LayoutInflater.from(context).inflate(R.layout.mybanner, this, true);
    }

    /*@Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        flag=1;
        vp_banner = (ViewPager) view.findViewById(R.id.vp_banner);
        banner_points = (LinearLayout) view.findViewById(R.id.banner_points);
        list_iv = new ArrayList<>();
        imagePagerAdapter = new ImagePagerAdapter();
        vp_banner.setAdapter(imagePagerAdapter);
        vp_banner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
                int size = list.size();
                position %= size;
                if (position < 0) {
                    position = list.size() + position;
                }
                for (int i = 0; i < list.size(); i++) {
                    ((ImageView) banner_points.getChildAt(i)).setImageResource(R.mipmap.point1);
                }
                if (position == 0) {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point2);
                } else {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point2);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }*/

    public void init() {
        vp_banner = (ViewPager) view.findViewById(R.id.vp_banner);
        banner_points = (LinearLayout) view.findViewById(R.id.banner_points);
        list_iv = new ArrayList<>();
        imagePagerAdapter = new ImagePagerAdapter();
        vp_banner.setAdapter(imagePagerAdapter);
        vp_banner.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                index = position;
                int size = list.size();
                position %= size;
                if (position < 0) {
                    position = list.size() + position;
                }
                for (int i = 0; i < list.size(); i++) {
                    ((ImageView) banner_points.getChildAt(i)).setImageResource(R.mipmap.point1);
                }
                if (position == 0) {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point2);
                } else {
                    ((ImageView) banner_points.getChildAt(position)).setImageResource(R.mipmap.point2);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    public void setHomeBannerCall(HomeBannerCall homeBannerCall) {
        this.homeBannerCall = homeBannerCall;
    }

    public void setList(List<?> list) {
        this.list = list;
        if(flag==0){
            init();
        }
        AddContent();
    }

    public void start() {
        isStart = true;
        handler.postDelayed(runnable, Time);
    }

    public void stop() {
        isStart = false;
    }

    public void UpData(List<?> list) {
        this.list = list;
        AddContent();
        imagePagerAdapter.notifyDataSetChanged();
    }

    /**
     * 往list_iv中添加数据
     */
    private void AddContent() {
        if (list.size() != 0) {
            String string = list.get(0).getClass().getName();
            //Log.i("MyBanner","name=="+string);
            //加载本地数据
            if (string.endsWith("Integer")) {
                list_iv.clear();
                for (int i = 0; i < list.size(); i++) {
                    ImageView iv = new ImageView(context);
                    iv.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
                    iv.setScaleType(ImageView.ScaleType.FIT_XY);
                    iv.setImageResource((Integer) list.get(i));
                    list_iv.add(iv);
                }
            }
            //加载网络数据
            if (string.endsWith("String")) {
                list_iv.clear();
                for (int i = 0; i < list.size(); i++) {
                    ImageView iv = new ImageView(context);
                    iv.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(context)
                            .load(Constants.SERVICE_IP + list.get(i).toString())
                            .diskCacheStrategy(DiskCacheStrategy.ALL)
                            .into(iv);
                    list_iv.add(iv);
                }
            }
        }
        //加载小点
        banner_points.removeAllViews();
        for (int i = 0; i < list.size(); i++) {
            ImageView view = new ImageView(context);
            view.setScaleType(ImageView.ScaleType.CENTER);
            banner_points.addView(view);
            if (i == 0) {
                view.setImageResource(R.mipmap.point2);
            } else {
                view.setImageResource(R.mipmap.point1);
            }
            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view.getLayoutParams();
            params.rightMargin = 10;
            params.width = 15;
            params.height = 15;
            view.setLayoutParams(params);
        }
        if (list != null && list.size() != 0) {
            vp_banner.setCurrentItem(list.size());
        }
    }

    class ImagePagerAdapter extends PagerAdapter {

        @Override
        public int getCount() {
            return Integer.MAX_VALUE;
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(final ViewGroup container, int position) {
            //改变位置使之在size之内
            //Log.i("MyBanner","position==="+position);
            ViewParent vp = null;
            if (list != null && list.size() != 0) {
                int size = list.size();
                position %= size;
                if (position < 0) {
                    position = list.size() + position;
                }
                if(list_iv!=null&&list_iv.size()!=0){
                    vp = list_iv.get(position).getParent();
                    //如果View已经在之前添加到了一个父组件，则必须先remove，否则会抛出IllegalStateException。
                    if (vp != null) {
                        ViewGroup parent = (ViewGroup) vp;
                        parent.removeView(list_iv.get(position));
                    }
                    //Log.i("MyBanner","position==nnnn="+position);
                    container.addView(list_iv.get(position));
                    //添加监听点击事件
                    final int finalPosition = position;
                    list_iv.get(position).setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            homeBannerCall.onClick(view, finalPosition);
                        }
                    });
                    //Log.i("MyBanner","add===添加"+position);
                    return list_iv.get(position);
                }else{
                    return null;
                }

            } else {
                return null;
            }
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            //Log.i("MyBanner","准备移除"+position);
            if (list != null && list.size() != 0) {
                position %= list.size();
                if (position < 0) {
                    position = list.size() + position;
                }
                //Log.i("MyBanner","remove===移除"+position);
                if(list_iv!=null&&list_iv.size()!=0){
                    container.removeView(list_iv.get(position));
                }

            }
        }
    }
}
